package com.zcgame.floatview

import android.animation.Animator
import android.animation.AnimatorSet
import android.animation.ObjectAnimator
import android.animation.ValueAnimator
import android.annotation.SuppressLint
import android.content.Context
import android.graphics.Color
import android.graphics.PixelFormat.RGBA_8888
import android.graphics.drawable.GradientDrawable
import android.media.Image
import android.os.Build
import android.util.AttributeSet
import android.util.Log
import android.view.*
import android.view.Gravity.*
import android.view.animation.AccelerateDecelerateInterpolator
import android.widget.FrameLayout
import android.widget.ImageView
import android.widget.TextView
import androidx.annotation.RequiresApi
import androidx.core.animation.*
import kotlin.math.abs

/**
 *@author:huangLJ
 *@date:2021/4/27 16:23
 */
@Suppress("DEPRECATION")
/**
 * 请务必先调用[setLayout]方法
 */
class FloatView @JvmOverloads constructor(
    context: Context, attributeSet: AttributeSet? = null,defAttr:Int = 0)
    : FrameLayout(context,attributeSet,defAttr) {

    private var mParams:WindowManager.LayoutParams
    private val windowManager:WindowManager
    private var mdownX:Float? = 0f
    private var mdownY:Float? = 0f
    private var mStartX:Float? = 0f
    private var mStartY:Float? = 0f
    private val dp3 = DensityUtil.dip2px(5.0f)
    private var mContext:Context = context
    private var screenWidth = 0
    private var screenHeight = 0
    private var toChangeX = 0//边缘的x坐标
    private var toChangeY = 0//边缘的y坐标
    private var toHideX = -width/2//隐藏的x坐标
    private var isLeft = true//判断view是在左边还是右边

    private var isMoved = false//判断当前view是不是在移动


    private lateinit var imageView:ImageView
    private lateinit var additionText:TextView
    companion object{
        private const val TAG = "FloatView"
        private const val WIDTH_SIZE = 45F //悬浮窗宽
        private const val HEIGHT_SIZE = 45F //悬浮窗高
    }


    //展开的动画
    private val unFoldAnimator = ObjectAnimator.ofFloat(this@FloatView, "translationX", 0f).apply {

    }
    //左边隐藏的动画
    private lateinit var hideAnimator:ObjectAnimator

    private lateinit var animatorSet: AnimatorSet



    init {
        mParams = WindowManager.LayoutParams()
        windowManager = context.getSystemService(Context.WINDOW_SERVICE) as WindowManager
    }

    /**
     * 设置图片或者文字
     */
    @SuppressLint("ClickableViewAccessibility", "WrongViewCast")
    fun setLayout(mipmap_id:Int):FloatView{
        imageView = ImageView(mContext)
        imageView.setImageResource(mipmap_id)
        imageView.layoutParams = LayoutParams( DensityUtil.dip2px(WIDTH_SIZE), DensityUtil.dip2px(
            HEIGHT_SIZE
        ))
        mParams = WindowManager.LayoutParams().apply {
            type = 2
            width = WindowManager.LayoutParams.WRAP_CONTENT
            height = WindowManager.LayoutParams.WRAP_CONTENT
            flags = WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE
            format = RGBA_8888
            gravity = START//设置成start或者left后view的基准点就已左边缘为坐标
            x = 0
            y = 0
        }
        //this.layoutParams = mParams
        this.addView(imageView)
        return this
    }

    /**
     * 设置附加信息
     */
    fun setAdditionText(text:String):FloatView{
        additionText = TextView(context).apply {
            layoutParams = FrameLayout.LayoutParams(LayoutParams.WRAP_CONTENT,LayoutParams.WRAP_CONTENT).apply {
            }
            textSize = 10F
            setTextColor(android.graphics.Color.parseColor("#ffffff"))
            setPadding(DensityUtil.dip2px(5f),0,DensityUtil.dip2px(5f),0)
            gravity = CENTER
            this.text = text
        }
        val gd = GradientDrawable().apply {
            setColor(Color.parseColor("#ff5d5d"))
            //cornerRadius  = DensityUtil.dip2px(5f).toFloat()
            cornerRadii = floatArrayOf(DensityUtil.dip2px(8f).toFloat(),DensityUtil.dip2px(8f).toFloat(),
                    0f,0f,DensityUtil.dip2px(8f).toFloat(),DensityUtil.dip2px(8f).toFloat(),0f,0f)
        }
        additionText.background = gd
        this.addView(additionText)
        return this
    }


    fun show(){
        windowManager.addView(this,mParams)

        postDelayed({
            setTextShow(isLeft)
            ObjectAnimator.ofFloat(this,"translationX", -width/2.toFloat()).apply{
                duration = 300L
                startDelay = 1000L
            }.start()
        },1000)
    }

    fun close(){
        windowManager.removeView(this)
    }



    override fun onDetachedFromWindow() {
        super.onDetachedFromWindow()
        this.removeAllViews()
        windowManager.removeView(this)
    }

    override fun onTouchEvent(event: MotionEvent?): Boolean {
        this.translationX = 0f
        //this.clearAnimation()
        when(event?.action){
            MotionEvent.ACTION_DOWN ->{
                unFoldAnimator.start()
                mStartX = mParams.x.toFloat()
                mStartY = mParams.y.toFloat()
                mdownX = event.rawX
                mdownY = event.rawY
            }
            MotionEvent.ACTION_MOVE -> {
                isMoved = true
                mParams.x = (event.rawX - mdownX!! + mStartX!!).toInt()
                mParams.y = (event.rawY - mdownY!! + mStartY!!).toInt()
                //printDebug(TAG,mParams.x.toString())
                //printDebug(TAG,(event.rawX-mdownX!!).toString())
                windowManager.updateViewLayout(this,mParams)

            }
            MotionEvent.ACTION_UP -> {
                isMoved = false
                //printDebug(TAG,"cancel")
                if(abs(event.rawX - mdownX!!) <= 5 && abs(event.rawY - mdownY!!) <= 5){
                    //TODO:开启点击事件
                    printDebug("you chick this float")
                }
                touchUp()
            }
            MotionEvent.ACTION_CANCEL -> {
                printDebug(TAG,"CANCEL")
            }
        }
        return super.onTouchEvent(event)
    }

    @SuppressLint("RtlHardcoded")
    private fun touchUp() {
        screenWidth = windowManager.defaultDisplay.width
        screenHeight = windowManager.defaultDisplay.height
        toChangeX = if(mParams.x < screenWidth/2){
            isLeft = true
            imageView.layoutParams = LayoutParams( DensityUtil.dip2px(WIDTH_SIZE), DensityUtil.dip2px(
                    HEIGHT_SIZE
            )).apply {
            }
            invalidate()
            0
        }else {
            isLeft = false
            imageView.layoutParams = LayoutParams( DensityUtil.dip2px(WIDTH_SIZE), DensityUtil.dip2px(
                    HEIGHT_SIZE
            )).apply {
                leftMargin = imageView.width/2
            }
            invalidate()
            screenWidth-width
        }
        //toChangeY = if(mParams.y < screenHeight/2) 0 else screenHeight - height
        toHideX = if(isLeft){-imageView.width/2}else{imageView.width/2}
        setTextShow(isLeft)

        //当前位置到边缘位置的动画
        val valueAnimator = ValueAnimator.ofFloat(mParams.x.toFloat(), toChangeX.toFloat()).apply {
            duration = 300L
            setTarget(this)
            interpolator = AccelerateDecelerateInterpolator()
            addUpdateListener {
                isMoved = true
                //printDebug(TAG,"数字: ${animatedValue as Float}")
                mParams.x = (it.animatedValue as Float).toInt()
                windowManager.updateViewLayout(this@FloatView, mParams)
            }
            doOnEnd { isMoved = false }
            doOnCancel { isMoved = false }
        }
        //半隐藏的动画
        hideAnimator = ObjectAnimator.ofFloat(this,"translationX", toHideX.toFloat()).apply{
            duration = 300L
            startDelay = 1000L

        }
        //两者组合起来
        animatorSet = AnimatorSet().apply {
            playSequentially(valueAnimator,hideAnimator)
            if(::animatorSet.isInitialized){
                if(isMoved|| animatorSet.isStarted || animatorSet.isRunning){
                    animatorSet.cancel()
                    hideAnimator.cancel()
                    this@FloatView.translationX = 0f
                }
            }
            start()
        }
    }

    /**
     *
     * 设置文字左显示还是右显示
     */
    private fun setTextShow(isLeft: Boolean) {

        if (isLeft) {
            additionText.layoutParams = LayoutParams(LayoutParams.WRAP_CONTENT,LayoutParams.WRAP_CONTENT).apply {
                leftMargin = imageView.width/2
            }
        }else{
            additionText.layoutParams = LayoutParams(LayoutParams.WRAP_CONTENT,LayoutParams.WRAP_CONTENT).apply {
            }
        }
        invalidate()
    }
}
